/* 调用 方式
String dateStr1=“2018-08-30 19：00：00.000”
WindowsSetSystemTime w=new WindowsSetSystemTime();
            w.SetLocalTime(
                    Short.parseShort(dateStr1.substring(0, 4).trim()),
                    Short.parseShort(dateStr1.substring(5, 7).trim()),
                    Short.parseShort(dateStr1.substring(8, 10).trim()),
                    Short.parseShort(dateStr1.substring(11, 13).trim()),
                    Short.parseShort(dateStr1.substring(14, 16).trim()),
                    Short.parseShort(dateStr1.substring(17, 19).trim()),
                    Short.parseShort(dateStr1.substring(20, 23).trim())
            );
 */
package org.longteng.sys;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinBase.SYSTEMTIME;
import com.sun.jna.win32.StdCallLibrary;

/**
 * 修改windows 精确到毫秒
 * <br>通过系统dll方式，因通过调用date命令权限有问题
 */
public class JnaWindowsSetSystemTime {

    /**
     * Kernel32 DLL Interface. kernel32.dll uses the __stdcall calling
     * convention (check the function declaration for "WINAPI" or "PASCAL"), so
     * extend StdCallLibrary Most C libraries will just extend
     * com.sun.jna.Library,
     */
    public interface Kernel32 extends StdCallLibrary {

        boolean SetLocalTime(SYSTEMTIME st);
        // loadLibrary()已经过时(deprecated)了
        Kernel32 instance = (Kernel32) Native.load("kernel32.dll", Kernel32.class);

    }

    /**
     * 设置系统时间
     * @param st
     * @return
     */
    private boolean SetLocalTime(SYSTEMTIME st) {
        return Kernel32.instance.SetLocalTime(st);
    }

    /**
     * 设置系统时间
     * @param wYear
     * @param wMonth
     * @param wDay
     * @param wHour
     * @param wMinute
     * @param wSecond
     * @param wMilliseconds
     * @return
     */
    public boolean SetLocalTime(short wYear, short wMonth, short wDay, short wHour, short wMinute, short wSecond , short wMilliseconds) {
        SYSTEMTIME st = new SYSTEMTIME();
        st.wYear = wYear;
        st.wMonth = wMonth;
        st.wDay = wDay;
        st.wHour = wHour;
        st.wMinute = wMinute;
        st.wSecond = wSecond;
        st.wMilliseconds=wMilliseconds;
        return SetLocalTime(st);
    }
}
